using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Win32;
using Microsoft.LearningComponents;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePointLearningKit;
class Program
{
static DirectoryEntries s_computerChildren;
static DirectoryEntry s_guests;
static void Main(string[] args)
{
Stack<IDisposable> disposer = new Stack<IDisposable>();
int rowNumber = 0;
try
{
string path;
if (args.Length == 1)
path = args[0];
else
{
path = Path.Combine(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location), "ProvisionData.xls");
}
List<List<string>> rows = LoadXmlSpreadsheet(path, "Provisioning Data");
DirectoryEntry computer = new DirectoryEntry(
String.Format("WinNT://{0},computer", Environment.MachineName));
disposer.Push(computer);
s_computerChildren = computer.Children;
s_guests = s_computerChildren.Find("Guests", "group");
disposer.Push(s_guests);
foreach (List<string> row in rows)
{
rowNumber++;
if ((row.Count == 0) || row[0].StartsWith(";"))
continue;
if (row[0] == "PauseAndQuit")
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
break;
}
Console.WriteLine("-- Row {0} of {1} --", rowNumber, rows.Count);
switch (row[0])
{
case "AddManagedPath":
ExpectCells(row, 3);
AddManagedPath(row[1], row[2]);
break;
case "CreateSiteCollection":
ExpectCells(row, 3);
CreateSiteCollection(row[1], row[2]);
break;
case "ConfigureSiteCollectionForSlk":
ExpectCells(row, 4);
ConfigureSiteCollectionForSlk(row[1], row[2], row[3]);
break;
case "CreateWebSite":
ExpectCells(row, 4);
CreateWebSite(row[1], row[2], row[3]);
break;
case "ActivateFeatureOnWebSite":
ExpectCells(row, 3);
ActivateFeatureOnWebSite(row[1], row[2]);
break;
case "CreateUser":
ExpectCells(row, 4);
CreateUser(row[1], row[2], row[3]);
break;
case "AddUserToSiteCollection":
ExpectCells(row, 4);
AddUserToSiteCollection(row[1], row[2], row[3]);
GrantUserAccess(row[1], "Read", row[3]);
break;
case "GrantUserAccess":
ExpectCells(row, 4);
GrantUserAccess(row[1], row[2], row[3]);
break;
case "AddToUserWebList":
ExpectCells(row, 4);
AddToUserWebList(row[1], row[2], row[3]);
break;
default:
throw new Exception(String.Format("Unknown command: {0}", row[0]));
}
}
Console.WriteLine("Done.");
}
#if !DEBUG
catch (Exception ex)
{
if (rowNumber > 0)
Console.WriteLine("Error: Row {0}: {1}", rowNumber, ex.Message);
else
Console.WriteLine("Error: {0}", ex.Message);
}
#endif
finally
{
while (disposer.Count > 0)
disposer.Pop().Dispose();
}
}
static List<List<string>> LoadXmlSpreadsheet(string fileName, string worksheetName)
{
XPathNavigator rootNode;
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite))
{
rootNode = new XPathDocument(stream).CreateNavigator();
}
string ssNamespace = "urn:schemas-microsoft-com:office:spreadsheet";
XmlNamespaceManager nsm = new XmlNamespaceManager(rootNode.NameTable);
nsm.AddNamespace("ss", ssNamespace);
XPathNavigator worksheetNode = rootNode.SelectSingleNode(
String.Format("ss:Workbook/ss:Worksheet[@ss:Name = '{0}']", worksheetName), nsm);
if (worksheetNode == null)
throw new Exception(String.Format("Worksheet not found: {0}", worksheetName));
List<List<string>> rows = new List<List<string>>();
foreach (XPathNavigator rowNode in worksheetNode.Select("ss:Table/ss:Row", nsm))
{
if (rowNode.MoveToAttribute("Index", ssNamespace))
{
while (rows.Count < rowNode.ValueAsInt - 1)
rows.Add(new List<string>());
rowNode.MoveToParent();
}
List<string> cells = new List<string>();
foreach (XPathNavigator cellNode in rowNode.Select("ss:Cell", nsm))
{
if (cellNode.MoveToAttribute("Index", ssNamespace))
{
while (cells.Count < cellNode.ValueAsInt - 1)
cells.Add(String.Empty);
cellNode.MoveToParent();
}
XPathNavigator dataNode = cellNode.SelectSingleNode("ss:Data", nsm);
if (dataNode != null)
cells.Add(dataNode.Value.Trim());
}
while ((cells.Count > 0) && (cells[cells.Count - 1].Length == 0))
cells.RemoveAt(cells.Count - 1);
rows.Add(cells);
}
return rows;
}
static void ExpectCells(List<string> row, int count)
{
if (row.Count != count)
{
throw new Exception(String.Format("Expecting {0} cells, found {1} cells",
count, row.Count));
}
}
static void CreateUser(string loginName, string fullName, string password)
{
Console.WriteLine("Finding or creating user account \"{0}\"", loginName);
if (loginName.StartsWith(@".\"))
loginName = loginName.Substring(2);
DirectoryEntry user;
bool existed;
try
{
user = s_computerChildren.Find(loginName, "user");
existed = true;
Console.WriteLine("...exists already");
}
catch (COMException)
{
user = s_computerChildren.Add(loginName, "user");
existed = false;
}
using (user)
{
if (!existed)
{
user.Invoke("SetPassword", new object[] { password });
user.Invoke("Put", new object[] { "FullName", fullName });
user.Invoke("Put", new object[] { "Description",
"* Created by SharePoint Learning Kit sample code *" });
user.CommitChanges();
try
{
s_guests.Invoke("Add", new object[] { user.Path });
}
catch (TargetInvocationException)
{
}
}
#if false
// add the user to SharePoint
string domainName = String.Format(@"{0}\{1}", s_parentWeb.Site.HostName, loginName);
s_parentWeb.SiteUsers.Add(domainName, String.Empty, fullName, String.Empty);
#endif
}
if (!existed)
Console.WriteLine("...created");
}
static void AddManagedPath(string webApplicationUrl, string relativeUrl)
{
Console.WriteLine("Finding or creating managed path \"{0}\" under \"{1}\"", relativeUrl,
webApplicationUrl);
SPWebApplication webApp = SPWebApplication.Lookup(new Uri(webApplicationUrl));
if (webApp.Prefixes.Contains(relativeUrl))
Console.WriteLine("...exists already");
else
{
webApp.Prefixes.Add(relativeUrl, SPPrefixType.WildcardInclusion);
Console.WriteLine("...created");
}
}
static void CreateSiteCollection(string siteCollectionUrl, string title)
{
Console.WriteLine("Finding or creating site collection \"{0}\"", siteCollectionUrl);
string loginName;
using (WindowsIdentity currentUser = WindowsIdentity.GetCurrent())
loginName = currentUser.Name;
try
{
using (SPSite spSite = new SPSite(siteCollectionUrl))
{
Console.WriteLine("...exists already");
return;
}
}
catch (FileNotFoundException)
{
}
SPWebApplication webApp = SPWebApplication.Lookup(new Uri(siteCollectionUrl));
using (SPSite spSite = webApp.Sites.Add(siteCollectionUrl, loginName, String.Empty))
{
using (SPWeb spWeb = spSite.RootWeb)
{
spWeb.Title = title;
spWeb.Update();
}
Console.WriteLine("...created");
}
}
static void ActivateFeatureOnWebSite(string webSiteUrl, string featureName)
{
Console.WriteLine("Activating feature \"{0}\" on Web site \"{1}\"", featureName,
webSiteUrl);
using (SPSite spSite = new SPSite(webSiteUrl))
{
SPFeatureDefinition featureDefinition =
spSite.WebApplication.Farm.FeatureDefinitions[featureName];
if (featureDefinition == null)
throw new Exception(String.Format("Feature \"{0}\" not found", featureName));
using (SPWeb spWeb = spSite.OpenWeb())
{
SPFeature feature = spWeb.Features[featureDefinition.Id];
if (feature != null)
Console.WriteLine("...exists already");
else
{
spWeb.Features.Add(featureDefinition.Id);
Console.WriteLine("...created");
}
}
}
}
static void ConfigureSiteCollectionForSlk(string siteCollectionUrl, string databaseServer,
string databaseName)
{
Console.WriteLine("Configuring site collection \"{0}\" for use with SLK",
siteCollectionUrl);
string sharePointLocation;
using (RegistryKey registryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
@"Software\Microsoft\Shared Tools\Web Server Extensions\12.0"))
{
object value;
if ((registryKey == null) || ((value = registryKey.GetValue("Location")) == null))
throw new Exception("SharePoint is not installed");
sharePointLocation = value.ToString();
}
string slkAdminLocation = Path.Combine(sharePointLocation,
@"Template\Admin\SharePointLearningKit");
if (!Directory.Exists(slkAdminLocation))
throw new Exception("SharePoint Learning Kit is not installed");
using (SPSite spSite = new SPSite(siteCollectionUrl))
{
string currentDatabaseServer, currentDatabaseName, instructorPermission,
learnerPermission;
bool createDatabase, createPermissions;
bool mappingFound = SlkAdministration.LoadConfiguration(spSite.ID,
out currentDatabaseServer, out currentDatabaseName, out createDatabase,
out instructorPermission, out learnerPermission, out createPermissions);
if (databaseServer == "CurrentOrDefaultServer")
databaseServer = currentDatabaseServer;
else
if (databaseServer == "localhost")
databaseServer = spSite.HostName;
if (databaseName == "CurrentOrDefaultDatabase")
databaseName = currentDatabaseName;
string schemaFileContents;
if (createDatabase)
{
schemaFileContents = File.ReadAllText(
Path.Combine(slkAdminLocation, "SlkSchema.sql"));
Console.WriteLine("...database doesn't exist -- creating it");
}
else
{
schemaFileContents = null;
Console.WriteLine("...database exists already");
}
string settingsFileContents = File.ReadAllText(
Path.Combine(slkAdminLocation, "SlkSettings.xml.dat"));
SlkAdministration.SaveConfiguration(spSite.ID, databaseServer, databaseName,
schemaFileContents, instructorPermission, learnerPermission, createPermissions,
null, settingsFileContents, spSite.WebApplication.ApplicationPool.Username,
ImpersonationBehavior.UseOriginalIdentity);
}
}
static void CreateWebSite(string parentWebSiteUrl, string relativeUrl, string title)
{
Console.WriteLine("Finding or creating Web site \"{0}\" under \"{1}\"", relativeUrl,
parentWebSiteUrl);
using (SPSite spSite = new SPSite(parentWebSiteUrl))
{
using (SPWeb parentWeb = spSite.OpenWeb())
{
SPWeb spWeb;
try
{
using (spWeb = parentWeb.Webs[relativeUrl])
{
if (!spWeb.Exists)
throw new System.IO.FileNotFoundException();
Console.WriteLine("...exists already");
return;
}
}
catch (System.IO.FileNotFoundException)
{
}
using (spWeb = parentWeb.Webs.Add(relativeUrl, title, String.Empty,
(uint) parentWeb.Locale.LCID, "STS", true, false))
{
SPNavigationNode node = new SPNavigationNode(spWeb.Title, relativeUrl);
if (parentWeb.Navigation.QuickLaunch != null)
parentWeb.Navigation.QuickLaunch.AddAsLast(node);
}
Console.WriteLine("...created");
}
}
}
static void AddUserToSiteCollection(string loginName, string fullName, string siteCollectionUrl)
{
Console.WriteLine("Adding user \"{0}\" to SharePoint site collection \"{1}\"", loginName,
siteCollectionUrl);
using (SPSite spSite = new SPSite(siteCollectionUrl))
{
if (loginName.StartsWith(@".\"))
loginName = String.Format(@"{0}\{1}", spSite.HostName, loginName.Substring(2));
using (SPWeb rootWeb = spSite.RootWeb)
rootWeb.SiteUsers.Add(loginName, String.Empty, fullName, String.Empty);
}
}
static void GrantUserAccess(string loginName, string permissions, string webSiteUrl)
{
Console.WriteLine("Giving \"{0}\" permission(s) \"{1}\" on \"{2}\"", loginName,
permissions, webSiteUrl);
using (SPSite spSite = new SPSite(webSiteUrl))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
if (loginName.StartsWith(@".\"))
loginName = String.Format(@"{0}\{1}", spSite.HostName, loginName.Substring(2));
SPUser spUser = spWeb.SiteUsers[loginName];
foreach (string substring in permissions.Split(','))
{
string permission = substring.Trim();
SPRoleAssignment roleAssignment = new SPRoleAssignment(spUser);
SPRoleDefinition roleDefinition;
try
{
roleDefinition = spWeb.RoleDefinitions[permission];
}
catch (SPException)
{
throw new Exception(String.Format(
"Cannot access permission \"{0}\"", permission));
}
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
spWeb.RoleAssignments.Add(roleAssignment);
}
}
}
}
static void AddToUserWebList(string loginName, string siteCollectionUrl, string webSiteUrl)
{
Console.WriteLine("Adding \"{0}\" to the user web list of \"{1}\" in \"{2}\"", webSiteUrl,
loginName, siteCollectionUrl);
Stack<IDisposable> disposer = new Stack<IDisposable>();
try
{
SPSite currentUserSite = new SPSite(siteCollectionUrl);
disposer.Push(currentUserSite);
if (loginName.StartsWith(@".\"))
{
loginName = String.Format(@"{0}\{1}", currentUserSite.HostName,
loginName.Substring(2));
}
using (SPWeb rootWeb = currentUserSite.RootWeb)
{
SPUser spUser = rootWeb.AllUsers[loginName];
SPSite destinationSite = new SPSite(siteCollectionUrl, spUser.UserToken);
disposer.Push(destinationSite);
SPWeb destinationWeb = destinationSite.OpenWeb();
disposer.Push(destinationWeb);
SlkStore slkStore = SlkStore.GetStore(destinationWeb);
SPSite sourceSite = new SPSite(webSiteUrl, spUser.UserToken);
disposer.Push(sourceSite);
SPWeb sourceWeb = sourceSite.OpenWeb();
disposer.Push(sourceWeb);
slkStore.AddToUserWebList(sourceWeb);
}
}
finally
{
while (disposer.Count > 0)
disposer.Pop().Dispose();
}
}
}